#include <iostream>
#include <unordered_map>
#include <vector>

using i64 = long long;

constexpr int N = 4E4 + 5;
constexpr int K = 19;

std::unordered_map<int, int> m;
int idx;
int get(int x) {
    if (!m.count(x)) {
        m[x] = ++idx;
    }
    return m[x];
}

std::vector<int> adj[N];

int f[N][K];
int dep[N];

void dfs(int u, int fa) {
    dep[u] = dep[fa] + 1;
    for (int i = 1; i < K; ++i) {
        f[u][i] = f[f[u][i - 1]][i - 1];
    }
    for (int v : adj[u]) {
        dfs(v, u);
    }
}

int lca(int x, int y) {
    if (dep[x] < dep[y]) {
        std::swap(x, y);
    }
    for (int i = K - 1; i >= 0; --i) {
        if (dep[f[x][i]] >= dep[y]) {
            x = f[x][i];
        }
    }
    if (x == y) {
        return x;
    }
    for (int i = K - 1; i >= 0; --i) {
        if (f[x][i] != f[y][i]) {
            x = f[x][i];
            y = f[y][i];
        }
    }
    return f[x][0];
}

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int n;
    std::cin >> n;
    
    int root;
    for (int i = 0; i < n; ++i) {
        int u, v;
        std::cin >> u >> v;
        if (v == -1) {
            root = get(u);
        } else {
            u = get(u), v = get(v);
            f[u][0] = v;
            adj[v].push_back(u);
        }
    }
    
    dfs(root, root);
    // std::cout << "root  = " << root << "\n";
    
    int m;
    std::cin >> m;
    
    while (m--) {
        int x, y;
        std::cin >> x >> y;
        x = get(x), y = get(y);
        
        int p = lca(x, y);
        
        if (x != p && y != p) {
            std::cout << "0\n";
        } else {
            std::cout << (x == p ? 1 : 2) << "\n";
        }
    }

    return 0;
}